package com.example.LibrarySystem.interceptor;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.jwt.JWTException;
import com.example.LibrarySystem.Exception.ServiceException;
import com.example.LibrarySystem.mapper.UserMapper;
import com.example.LibrarySystem.pojo.User;
import com.example.LibrarySystem.service.UserService;
import com.example.LibrarySystem.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * 自定义拦截器
 */

@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;

    /**
     * preHandle：在请求到达处理器之前执行，可以用于权限验证、数据校验等操作。如果返回true，则继续执行后续操作；如果返回false，则中断请求处理。
     * postHandle：在处理器处理请求之后执行，可以用于日志记录、缓存处理等操作。
     * afterCompletion：在视图渲染之后执行，可以用于资源清理等操作。
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /**
         * 验证是否登录
         */
        String token = request.getHeader("Authorization");
//        System.out.println(token);
        if(token == null){
            throw new ServiceException("500","token不存在");
        }

        int id = JwtUtil.verify(token);

        System.out.println(userService);

//        System.out.println(id);
        User user;
        try {
            user = userService.getUserById(id);
        }catch (JWTException e){
            throw new ServiceException("500","token异常或不存在");
        }

        if(!BeanUtil.isEmpty(user)){
            return true;
        }else {
            throw new ServiceException("500","token异常或不存在");
        }
    }
}
